
function research_form(divobj, input_string)
{
    var document_area = divobj;
    document_area.html("<input type='text'><button>Seek</button>");
    document_area.append("<hr/>");
    var research_area = $("<div id='research_area'></div>");
    document_area.append(research_area);
    
    var button = document_area.find("button");
    var entry = document_area.find("input");
    
    button.click(function() {
        var srsearch = entry.val();
		$.cookie("research_seek", srsearch);
        do_research(research_area, srsearch);
    });
	
	if (input_string == null) {
		input_string = $.cookie("research_seek");
	}
	
    if (input_string != null) {
        entry.val(input_string);
        do_research(research_area, input_string);
    }
}



function do_research(divarea, search_string)
{
    divarea.html(img_pending());
	divarea.append("Fetching...");
    
	var gathered = research_gather_get_cookie();
	
	divarea.load("/research/wiki", "search="+search_string,
	function() {
		divarea.append("<hr style='clear: left'></hr>");
		divarea.find("p").each(function() {
			var img = $("<img/>");
            var latex = $(this).text();
            img.attr('alt', latex);
			img.attr('src', COGS + "?" + latex);
			if ($.inArray(Base64.encode(latex), gathered) != -1) {
				img.addClass("gather");
				onImageGather(img);
			}
			img.load(function() {
                if (img.attr('height') > 60)
                    img.attr('height', 60);
			});
            img.click(function() {
                $(this).toggleClass("gather");
				research_gather_update_cookie(divarea);
				if ($(this).hasClass("gather"))
					onImageGather($(this));
				else
					onImageUngather($(this));
            });
			img.addClass("research");
			$(this).replaceWith(img);
		});
	});
}

function research_gather_update_cookie(divarea)
{
	var elements64 = [];
	divarea.find("img.gather").each(function() {
		elements64.push(Base64.encode($(this).attr('alt')));
	});
	var join64 = "";
	for (var i in elements64) {
		join64 = join64 + "|" + elements64[i];
	}
	$.cookie("research_gather", join64);
}

function research_gather_get_cookie()
{
	var value = $.cookie("research_gather");
	if (value != null)
		return value.split("|");
	else
		return [];
}


var notebooks = ["wiki:Algebra:Quadratic Equation",
                 "wiki:Algebra:Linear Algebra:Matrix",
                 "wiki:Algebra:Quadratic Function",
                 "wiki:Algebra:Linear Algebra:Vector Space",
                 "wiki:Number Theory:Chinese Remainder Theorem"]
                 
var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}
                 
function listFolder(path)
{
    var elements = {};
    for (var i in notebooks) {
        mo = notebooks[i].match(path+":([^:]+)(:.*)?");
        if (mo != null)
            elements[mo[1]] = 1;
    }
    var keys = getKeys(elements);
    keys.sort();
    return keys;
}

function fill(selectobj, array)
{
    for (var i in array) {
        var option = $("<option/>");
        option.text(array[i]);
        selectobj.append(option);
    }
}

function browse(selectobj, path)
{
	selectobj.attr('path', path);
    fill(selectobj, listFolder(path));
    selectobj.find("option").each(function() {
        var text = $(this).text();
        $(this).val(path + ":" + text);
        $(this).mouseenter(function() { overlib(text, WRAP); });
        $(this).mouseleave(function() { nd(); });
    });
}

function onSelectElementInFolder()
{
    $(this).next().remove();
    var path = $(this).find(":selected").val();
	if (path == null) return;
	
	var subfolder = $('<select size="4"/>');
    var span = subfolder.wrap("<span/>").parent();
    $(this).after(span);
    
    browse(subfolder, path);
    subfolder.click(onSelectElementInFolder);
    subfolder.focus();
    var p = $(this).closest(".finder").find("p");
	p.text(path);
	p.attr('title', $(this).find(":selected").text());
    notebook_load($('#notebook_area'), path, null);
}

function onImageGather(img)
{
	var td = $(".sorter").find("td");
	var gather_bin = $("#gather_bin");
	var existing = [];
	td.find("img").each(function() {
		if (img.attr('alt') == $(this).attr('alt'))
			existing.push($(this));
	});
	if (existing.length == 0) {
		var clone = img.clone();
		clone.click(onSorterImageClick);
		gather_bin.append(clone);
		gather_bin.append(" ");
	}
}

function onImageUngather(img)
{
	var td = $(".sorter").find("td");
	td.find("img").each(function() {
		if (img.attr('alt') == $(this).attr('alt'))
			$(this).remove();
	});
}

function onFolderAddClick()
{
	$('#new_notebook').dialog('open');
}

function onArrangeTabsClick()
{
	var path = $(".finder").find("p").text();
	var title = $(".finder").find("p").attr('title');
	var existing = $(".sorter").find("th[value=" + path + "]");
	$(".sorter th").removeClass("active_tab");
	if (existing.length == 0) {
		var th = research_sorter_addTab(title, path);
		th.addClass("active_tab");
		research_sorter_updateCookie();
	}
	else {
		existing.addClass("active_tab");
	}
}

function onSorterTabClick()
{
	$(this).closest("table").find("th").removeClass("active_tab");
	$(this).addClass("active_tab");
}

function onSorterTabDblClick()
{
	research_sorter_removeTab($(this));
	research_sorter_updateCookie();
}

function onSorterImageClick()
{
	$(this).remove();
	var active_sorter_tab = $(".sorter th.active_tab");
	active_sorter_tab.next().append($(this));
	var add_formula =  $(this).attr('alt');
	notebook_load($('#notebook_area'), active_sorter_tab.val(), null,
	function() {
		notebook_add($('#notebook_area'), add_formula, 'formula');
	});
}

function onNewNotebookCreate()
{
	var name = $('#new_notebook_name').val();
	$('#new_notebook_name').val('');
	var select = null;
	$('.finder select').each(function(){  select = $(this); });
	if (select != null) {
		var option = $("<option/>");
		option.text(name);
		option.val(select.attr('path') +":" + name);
		notebooks.push(option.val());
		select.append(option);
		option.attr('selected', 'selected');
		select.click();
	}
	$('#new_notebook').dialog('close');
}

function research_sorter_addTab(title, path)
{
	var new_row = $("<tr><th>?</th><td></td>");
	var th = new_row.find("th");
	th.text(title);
	th.val(path);
	th.click(onSorterTabClick);
	th.dblclick(onSorterTabDblClick);
	$(".sorter table").append(new_row);
	return th;
}

function research_sorter_removeTab(th)
{
	th.closest("tr").remove();
}

function research_sorter_applyCookie()
{
	var cookie = $.cookie('research_sorter');
	if (cookie != null) {
		var sorter_tabs = cookie.split("|");
		for (var i in sorter_tabs) {
			var path = sorter_tabs[i];
			if (path != "") {
				var title = path.substring(path.lastIndexOf(':')+1);
				research_sorter_addTab(title, path);
			}
		}
	}
}

function research_sorter_updateCookie()
{
	var sorter_tabs = [];
	$(".sorter th").each(function() {
		if ($(this).val())
			sorter_tabs.push($(this).val());
	});
	var join = ""
	for (var i in sorter_tabs) join = join + "|" + sorter_tabs[i];
	$.cookie('research_sorter', join);
}

function research_begin()
{
	$('#research_procedure').tabs({cookie: {expires: 7}});
	research_form($('#seek_knowledge'), null);
	$.get("/notebooks", "", function(data, status) {
		notebooks = [];
		$(data).find("li").each(function() {
			notebooks.push($(this).text());
		});
		browse($("#root"), ("wiki"));
	}, 'html');
    $("#root").click(onSelectElementInFolder);
	research_sorter_applyCookie();
	$('#new_notebook').dialog({autoOpen: false, modal: true,
		buttons: {'Create': onNewNotebookCreate }});
	$('#new_notebook_name').keypress(function(event) {
        if (event.keyCode == 13) onNewNotebookCreate();
	});
	$('#profit_notebooks').load("/notebooks");
}

